package com.example.order.service.impl;

import com.example.order.service.OrderService;
import com.example.order.vo.Order;
import com.example.product.vo.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public Order createOrder(Order order) {
        Product product = getProductFromRemote(order.getProductId());
        return order;
    }

    public Product getProductFromRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("shop-product");

        ServiceInstance serviceInstance = instances.get(0);

        // 远程url
//        String api = serviceInstance.getUri().toString() + "/products/" + productId;
        String api = "http://shop-product/products/" + productId;
        log.info("request api url: {}", api);

        Product product = restTemplate.getForObject(api, Product.class);
        return product;
    }
}
